import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../services/alger_api_service.dart';
import '../services/music_player_service.dart';
import '../widgets/song_list_widget.dart';
import '../widgets/mini_player_widget.dart';
import '../widgets/player_sheet_widget.dart';
import '../models/song.dart';
import 'alger_album_detail_screen.dart';

class AlgerArtistDetailScreen extends StatefulWidget {
  final String artistId;
  final String artistName;
  final String picUrl;
  const AlgerArtistDetailScreen({
    super.key,
    required this.artistId,
    required this.artistName,
    required this.picUrl,
  });

  @override
  State<AlgerArtistDetailScreen> createState() => _AlgerArtistDetailScreenState();
}

class _AlgerArtistDetailScreenState extends State<AlgerArtistDetailScreen> with TickerProviderStateMixin {
  final AlgerApiService _api = AlgerApiService();
  AlgerArtistDetail? _detail;
  List<Song> _hotSongs = [];
  List<AlgerAlbum> _albums = [];
  bool _loadingDetail = true;
  bool _loadingSongs = true;
  bool _loadingAlbums = true;
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _loadAll();
  }

  Future<void> _loadAll() async {
    _loadDetail();
    _loadHotSongs();
    _loadAlbums();
  }

  Future<void> _loadDetail() async {
    setState(() => _loadingDetail = true);
    try {
      final d = await _api.fetchArtistDetail(widget.artistId);
      if (mounted) setState(() { _detail = d; });
    } catch (e) {
      debugPrint('加载艺人详情失败: $e');
    } finally {
      if (mounted) setState(() => _loadingDetail = false);
    }
  }

  Future<void> _loadHotSongs() async {
    setState(() => _loadingSongs = true);
    try {
      final list = await _api.fetchArtistHotSongs(widget.artistId, limit: 50, offset: 0);
      if (mounted) setState(() { _hotSongs = list; });
    } catch (e) {
      debugPrint('加载热门歌曲失败: $e');
    } finally {
      if (mounted) setState(() => _loadingSongs = false);
    }
  }

  Future<void> _loadAlbums() async {
    setState(() => _loadingAlbums = true);
    try {
      final list = await _api.fetchArtistAlbums(widget.artistId, limit: 50, offset: 0);
      if (mounted) setState(() { _albums = list; });
    } catch (e) {
      debugPrint('加载专辑失败: $e');
    } finally {
      if (mounted) setState(() => _loadingAlbums = false);
    }
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final playerService = Provider.of<MusicPlayerService>(context, listen: false);
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.artistName),
        centerTitle: false,
        backgroundColor: Colors.white,
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(152),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildHeaderInAppBar(),
              TabBar(
                controller: _tabController,
                tabs: const [
                  Tab(text: '热门歌曲'),
                  Tab(text: '专辑'),
                  Tab(text: '艺人介绍'),
                ],
              ),
            ],
          ),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _loadingSongs
                    ? const Center(child: CircularProgressIndicator())
                    : SongListWidget(
                        songs: _hotSongs,
                        showRanking: true,
                        onSongTap: (song, index) async {
                          await playerService.setPlaylist(_hotSongs, startIndex: index);
                        },
                      ),
                _buildAlbums(),
                _buildIntro(),
              ],
            ),
          ),
          // 底部迷你播放器（仅在有歌曲时显示）
          Consumer<MusicPlayerService>(
            builder: (context, svc, child) {
              if (svc.currentSong == null) return const SizedBox.shrink();
              return MiniPlayerWidget(onTap: _showPlayerSheet);
            },
          ),
        ],
      ),
    );
  }

  void _showPlayerSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      constraints: const BoxConstraints(
        maxWidth: double.infinity,
        maxHeight: double.infinity,
      ),
      useSafeArea: true,
      builder: (context) => const PlayerSheetWidget(),
    );
  }

  // 放置在 AppBar.bottom 上方的艺人头像、名称与简介（两行）
  Widget _buildHeaderInAppBar() {
    final avatar = _detail?.avatarUrl ?? widget.picUrl;
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: SizedBox(
              width: 72,
              height: 72,
              child: CachedNetworkImage(
                imageUrl: avatar,
                fit: BoxFit.cover,
                memCacheWidth: 200,
                memCacheHeight: 200,
                maxWidthDiskCache: 200,
                maxHeightDiskCache: 200,
                placeholder: (context, url) => Container(color: Colors.grey[200]),
                errorWidget: (context, url, error) => Container(
                  color: Colors.grey[300],
                  child: const Icon(Icons.broken_image, size: 24),
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _detail?.name ?? widget.artistName,
                  style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 4),
                if ((_detail?.briefDesc ?? '').isNotEmpty)
                  Text(
                    _detail!.briefDesc!,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 12, color: Colors.grey[700]),
                  ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildHeader() {
    final avatar = _detail?.avatarUrl ?? widget.picUrl;
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: Colors.grey[200]!)),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: SizedBox(
              width: 72,
              height: 72,
              child: CachedNetworkImage(
                imageUrl: avatar,
                fit: BoxFit.cover,
                memCacheWidth: 200,
                memCacheHeight: 200,
                maxWidthDiskCache: 200,
                maxHeightDiskCache: 200,
                placeholder: (context, url) => Container(color: Colors.grey[200]),
                errorWidget: (context, url, error) => Container(
                  color: Colors.grey[300],
                  child: const Icon(Icons.broken_image, size: 24),
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _detail?.name ?? widget.artistName,
                  style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 4),
                if ((_detail?.briefDesc ?? '').isNotEmpty)
                  Text(
                    _detail!.briefDesc!,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 12, color: Colors.grey[700]),
                  ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildAlbums() {
    if (_loadingAlbums) {
      return const Center(child: CircularProgressIndicator());
    }
    if (_albums.isEmpty) {
      return const Center(child: Text('暂无专辑'));
    }
    return LayoutBuilder(
      builder: (context, constraints) {
        final isWide = constraints.maxWidth > 680;
        final crossAxisCount = isWide ? 5 : 3;
        final spacing = 12.0;
        return GridView.builder(
          padding: const EdgeInsets.all(16),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: crossAxisCount,
            crossAxisSpacing: spacing,
            mainAxisSpacing: spacing,
            childAspectRatio: 0.78,
          ),
          itemCount: _albums.length,
          itemBuilder: (context, index) {
            final a = _albums[index];
            return GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => AlgerAlbumDetailScreen(
                      albumId: a.id,
                      albumName: a.name,
                      coverUrl: a.picUrl,
                    ),
                  ),
                );
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: AspectRatio(
                      aspectRatio: 1,
                      child: CachedNetworkImage(
                        imageUrl: a.picUrl,
                        fit: BoxFit.cover,
                        memCacheWidth: 200,
                        memCacheHeight: 200,
                        maxWidthDiskCache: 200,
                        maxHeightDiskCache: 200,
                        placeholder: (context, url) => Container(color: Colors.grey[200]),
                        errorWidget: (context, url, error) => Container(
                          color: Colors.grey[300],
                          child: const Icon(Icons.broken_image, size: 20),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 6),
                  Text(
                    a.name,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(fontSize: 12),
                  ),
                  if ((a.publishDate ?? '').isNotEmpty) ...[
                    const SizedBox(height: 2),
                    Text(
                      a.publishDate!,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(fontSize: 11, color: Colors.grey[600]),
                    ),
                  ],
                ],
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildIntro() {
    if (_loadingDetail) {
      return const Center(child: CircularProgressIndicator());
    }
    final text = _detail?.briefDesc ?? '暂无介绍';
    return Padding(
      padding: const EdgeInsets.all(16),
      child: SingleChildScrollView(
        child: Text(
          text,
          style: const TextStyle(fontSize: 13, height: 1.6),
        ),
      ),
    );
  }
}
